package com.sljy.hzk.ui.detection;

import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.example.api.InjectParam;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sljy.hzk.R;
import com.sljy.hzk.annotation.ActivityInfo;
import com.sljy.hzk.base.BaseActivity;
import com.sljy.hzk.base.UserInfo;
import com.sljy.hzk.entity.DangerDatabaseEntity;
import com.sljy.hzk.entity.DetectionDangerEntity;
import com.sljy.hzk.entity.TaskDatabaseEntity;
import com.sljy.hzk.entity.TaskDetailEntity;
import com.sljy.hzk.entity.UserEntity;
import com.sljy.hzk.net.BaseCallBack;
import com.sljy.hzk.net.CommonResult;
import com.sljy.hzk.net.HttpHeper;
import com.sljy.hzk.net.service.DetectionService;
import com.sljy.hzk.room.AppDataBase;
import com.sljy.hzk.room.dao.DangerDao;
import com.sljy.hzk.util.TimeUtils;
import com.sljy.hzk.view.MarginItemDecoration;
import com.tkk.api.RxEventProcessor;
import com.trello.rxlifecycle2.android.ActivityEvent;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.functions.Consumer;

@ActivityInfo(layout = R.layout.activity_detection_fill_in,isShowActionBar = true, title = "", titleLevel = ActivityInfo.TITLE_TWO_LEVEL)
public class DetectionFillInActivity extends BaseActivity {
    @InjectParam
    int pId;//分区id
    @InjectParam
    String posName;//分区名字
    @InjectParam
    String recordName;//危害名称
    @InjectParam
    boolean isFromLocal = false;//是否是本地数据
    @InjectParam
    DangerDatabaseEntity databaseEntity;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_up)
    ImageButton tvUp;
    @BindView(R.id.tv_partition_info)
    TextView tvPartitionInfo;
    @BindView(R.id.recycer)
    RecyclerView recycerView;
    boolean isLoadFail = false;
    BaseQuickAdapter adapter;
    List<DetectionDangerEntity> dangerEntityList = new ArrayList<>();
    UserEntity user;
    DangerDao dangerDao;
    private int onlyId;

    @Override
    protected void init() {
        DetectionFillInActivity__JumpCenter.bind(this);
        if (isFromLocal) {
            onlyId = databaseEntity.getId();
            pId = databaseEntity.getpId();
            posName = databaseEntity.getPosName();
            recordName = databaseEntity.getRecordName();
        }
        user = UserInfo.getUserInfo();
        dangerDao = AppDataBase.getInstance().getDangerDao();
        tvTitle.setText(recordName);
        tvPartitionInfo.setText(posName);
        recycerView.setLayoutManager(new LinearLayoutManager(this));
        recycerView.addItemDecoration(new MarginItemDecoration(20));
        adapter = new BaseQuickAdapter<DetectionDangerEntity, BaseViewHolder>(R.layout.item_danger_fill_in, dangerEntityList) {
            @Override
            protected void convert(BaseViewHolder helper, final DetectionDangerEntity item) {
                helper.setText(R.id.tv_title, item.getHarmName());
                //1物理0化学
                boolean isWl = item.getType() == 1;
                helper.setText(R.id.edit1, item.getValue1());
                helper.setText(R.id.edit2, item.getValue2());
                helper.setText(R.id.edit3, item.getValue3());
                helper.setText(R.id.edit4, item.getMin());
                helper.setText(R.id.edit5, item.getPlace());
                helper.setText(R.id.tv_hint1, !isWl ? "PC-TWA" : "接触限值1");
                helper.setText(R.id.tv_hint2, !isWl ? "PC-STEL" : "接触限值2");
                helper.setText(R.id.tv_hint3, !isWl ? "MAC" : "接触限值3");
                ((EditText) helper.getView(R.id.edit1)).addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {
                        item.setValue1(s.toString());

                    }

                    @Override
                    public void afterTextChanged(Editable s) {

                    }
                });
                ((EditText) helper.getView(R.id.edit2)).addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {
                        item.setValue2(s.toString());

                    }

                    @Override
                    public void afterTextChanged(Editable s) {

                    }
                });
                ((EditText) helper.getView(R.id.edit3)).addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {
                        item.setValue3(s.toString());

                    }

                    @Override
                    public void afterTextChanged(Editable s) {

                    }
                });
                ((EditText) helper.getView(R.id.edit4)).addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {
                        item.setMin(s.toString());

                    }

                    @Override
                    public void afterTextChanged(Editable s) {

                    }
                });
                ((EditText) helper.getView(R.id.edit5)).addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {
                        item.setPlace(s.toString());
                    }

                    @Override
                    public void afterTextChanged(Editable s) {

                    }
                });
            }
        };
        recycerView.setAdapter(adapter);
        if (isFromLocal) {
            if (databaseEntity.isFinsh()) {
                tvUp.setVisibility(View.GONE);
            }
            Gson gson = new Gson();
            setData(gson.fromJson(databaseEntity.getDataJson(), new TypeToken<List<DetectionDangerEntity>>() {
            }.getType()));

        } else {
            HttpHeper.get().create(DetectionService.class)
                    .getHarmFactor(pId)
                    .compose(this.bindUntilEvent(ActivityEvent.DESTROY))
                    .compose(getThread())
                    .subscribe(new BaseCallBack<List<DetectionDangerEntity>>(this) {
                        @Override
                        public void onCallBackSuccess(List<DetectionDangerEntity> data) {
                            if (data != null && data.size() != 0) {
                                setData(data);
                            }else {
                                isLoadFail = true;
                                showToast("没有数据");
                            }
                        }

                        @Override
                        public void onFail(String mes) {
                            isLoadFail = true;
                            showToast(mes);
                        }
                    });
        }

    }

    private void setData(List<DetectionDangerEntity> data) {
        dangerEntityList.addAll(data);
        adapter.notifyDataSetChanged();
    }

    @OnClick(R.id.tv_up)
    void up() {
        if (dangerEntityList.size() == 0) {
            return;
        }
        String jsonData = dangerEntityList.toString();
        Log.d(TAG, ">>>up---" + jsonData);
        HttpHeper.get().create(DetectionService.class)
                .submit(user.getUserId(), recordName, pId, user.getComPId(), jsonData)
                .compose(this.bindUntilEvent(ActivityEvent.DESTROY))
                .compose(getThread())
                .doOnNext(objectCommonResult -> {

                })
                .subscribe(new BaseCallBack<Object>(this) {
                    @Override
                    public void onCallBackSuccess(Object data) {
                        showToast("上传成功");
                        List<DangerDatabaseEntity> list = dangerDao.getById(String.valueOf(user.getUserId()));
                        for(DangerDatabaseEntity l : list){
                            if(l.id == onlyId){
                                dangerDao.delete(l);
                                break;
                            }
                        }
                        RxEventProcessor.get().post("DetectionDataHaveChange");
                        finish();
                    }

                    @Override
                    public void onFail(String mes) {
                        showToast("提交失败，请检查网络链接\n或者返回点击返回按钮进行离线保存");
                    }
                });
    }

    @Override
    protected boolean isShouldHideInput(View v, MotionEvent event) {
        return false;
    }

    @Override
    protected void onBackClick() {
        onBackPressed();
    }

    @Override
    public void onBackPressed() {
        if(databaseEntity != null){
            if (databaseEntity.isFinsh()) {
                finish();
                return;
            }
        }
        new MaterialDialog.Builder(this)
                .content("当前检测没有提交，退出前是否保存到本地")
                .positiveText("保存到本地")
                .onPositive((dia, v) -> {
                    if (isFromLocal){
                        Log.d(TAG, ">>>beforeTextChanged---" + dangerEntityList.get(0).getPlace());
                        databaseEntity.setDataJson(dangerEntityList.toString());
                        databaseEntity.setTime(TimeUtils.getNowNyr());
                        dangerDao.update(databaseEntity);
                    }else {
                        dangerDao.insert(new DangerDatabaseEntity(false, recordName, pId, posName, TimeUtils.getNowNyr(), dangerEntityList.toString(),TimeUtils.dateToStrMd(TimeUtils.getNowDate()),String.valueOf(user.getUserId())));
                    }
                    RxEventProcessor.get().post("DetectionDataHaveChange");
                    showToast("保存成功");
                    finish();
                })
                .negativeText("直接退出")
                .onNegative((dialog, which) -> {
                    finish();
                })
                .show();
    }
}
